﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
using System.Collections;
using System.Text.RegularExpressions;
using System.Threading;

namespace Fetion
{
    public partial class myMainFrom : Form
    {
        DataSet ds = new DataSet();
        string[] sentNum;
        string myPhone;
        string myPSW;
        string sendText;
        Thread sendThread;
        public myMainFrom()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!System.IO.File.Exists("PhoneNum.xml"))
            {
                XmlDocument doc = new XmlDocument();
                XmlElement root = doc.CreateElement("phoneNum");
                doc.AppendChild(root);
                XmlElement friend = doc.CreateElement("friend");
                root.AppendChild(friend);
                XmlElement friName = doc.CreateElement("friName");
                friend.AppendChild(friName);
                XmlElement friNum = doc.CreateElement("friNum");
                friend.AppendChild(friNum);
                XmlElement mynum = doc.CreateElement("mynum");
                root.AppendChild(mynum);
                XmlElement myphonenum = doc.CreateElement("myphonenum");
                mynum.AppendChild(myphonenum);
                XmlElement mypsw = doc.CreateElement("mypsw");
                mynum.AppendChild(mypsw);
                doc.Save("PhoneNum.xml");
            }
            ds.ReadXml("PhoneNum.xml");
            bindingSource1.DataSource = ds.Tables[0];
            friendlist.DataSource = bindingSource1;
            BindMyNum();
        }
        public delegate void UpdateLableDelegate(string Num,string str);

        public void UpdateLable(string Num,string str)
        {
            labResult.Visible = true;
            labResult.Text = "发送给号码" + Num + "结果：" + str;
        }
        //发送短信
        private void btnSend_Click(object sender, EventArgs e)
        {
            labResult.Text = "";
            try
            {
                char[] charSeparators = new char[] { ';' };
                sentNum = textBoxfri.Text.Split(charSeparators,StringSplitOptions.RemoveEmptyEntries);
                myPhone = combMyNum.Text;
                myPSW = textBoxPSW.Text;
                sendText = richTextBox.Text;
                sendThread = new Thread(new ThreadStart(SendMail));
                sendThread.IsBackground = true;
                sendThread.Start();
            }
            catch (Exception)
            {
                
                labResult.Visible=true;
                labResult.Text = "发送出错";
            }
        }

        public void SendMail()
        {
            if (sentNum.Length != 0)
            {
                Encoding myEncoding = Encoding.GetEncoding("utf-8");
                foreach (string Num in sentNum)
                {
                    string address = "https://fetionapi.appspot.com/api/?from=" + myPhone + "&pw=" + myPSW + "&to=" + Num + "&msg=" + HttpUtility.UrlEncode(sendText, myEncoding);
                    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
                    req.Method = "GET";
                    using (WebResponse wr = req.GetResponse())
                    {
                        Stream resStream = wr.GetResponseStream();
                        StreamReader sr = new StreamReader(resStream, myEncoding);
                        string responseStr = sr.ReadToEnd();
                        UpdateLableDelegate updateLable = new UpdateLableDelegate(UpdateLable);
                        labResult.Invoke(updateLable, Num,responseStr);
                        sr.Close();
                    }
                    Thread.Sleep(6000);

                }
            }
           
        }

        //保存好友
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (System.IO.File.Exists("PhoneNum.xml"))
                {
                    System.IO.File.Delete("PhoneNum.xml");
                }
                ArrayList rowNum=new ArrayList() ;
                if (ds.Tables[0].Rows.Count > 1)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (ds.Tables[0].Rows[i][1].ToString() == "" & ds.Tables[0].Rows[i][0].ToString() == "")
                        {
                           rowNum.Add(i);
                        }
                    }
                }
                for (int i = 0; i < rowNum.Count; i++)
                {
                    ds.Tables[0].Rows.RemoveAt((int)rowNum[i] - i);
                }
                ds.WriteXml("PhoneNum.xml");
                labResult.Visible = true;
                labResult.Text = "保存好友成功";
            }
            catch (Exception)
            {
                labResult.Visible = true;
                labResult.Text = "保存好友失败";
            }
           
        }

        //删除选中好友
        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                ArrayList index=new ArrayList();
                foreach (DataGridViewRow row in friendlist.Rows)
                {
                    if (row.Cells[0].FormattedValue.ToString().ToLower() == "true")
                    {
                        index.Add(row.Index);
                    }
                }
                int n = 0;
                foreach (int i in index)
                {
                    //friendlist.Rows.RemoveAt(i);
                    ds.Tables[0].Rows.RemoveAt(i-n);
                    n++;
                }
                if (System.IO.File.Exists("PhoneNum.xml"))
                {
                    System.IO.File.Delete("PhoneNum.xml");
                }
                ds.WriteXml("PhoneNum.xml");
                labResult.Visible = true;
                labResult.Text = "删除好友成功";
            }
            catch (Exception)
            {
                labResult.Visible = true;
                labResult.Text = "删除好友失败";
            }
           
            
        }

        //把选中号码不重复地复制入发送号码textbox
        private void btnSentNum_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in friendlist.Rows)
            {
                if (row.Cells[0].FormattedValue.ToString().ToLower() == "true")
                {
                    string[] strNum = textBoxfri.Text.Split(';');
                    bool judge=true;
                    foreach (string str in strNum)
                    {
                        if (row.Cells[2].FormattedValue.ToString() == str)
                        {
                            judge = false;     
                        }
                    }
                    if (judge == true)
                    {
                        textBoxfri.Text += row.Cells[2].FormattedValue.ToString();
                        textBoxfri.Text += ";";
                    }
                }
            }
            textBoxfri.Text = DeleteDouble(textBoxfri.Text);
        }

        string returnstring="";
        private string DeleteDouble(string str)
        {
            if (str.Length <= 2)
            {
                return returnstring;
            }
            else if (str.Substring(str.Length - 2, 1) == ";")
            {
                str = str.Substring(0, str.Length - 1);
                DeleteDouble(str);
                return returnstring;
            }
            else
            {
                returnstring = str;
                return returnstring;
            }
        }

        //绑定我的号码和密码
        private void BindMyNum()
        {
            try
            {
                combMyNum.DataSource = ds.Tables[1];
                combMyNum.DisplayMember = "myphonenum";
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    if (dr[0].ToString() == combMyNum.Text && dr[1].ToString() != "")
                    {
                        Encrypt encrypt = new Encrypt(); 
                        textBoxPSW.Text = encrypt.decode(dr[1].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                labResult.Visible = true;
                labResult.Text = ex.ToString();
            }
            
            
        }

        private void combMyNum_SelectedIndexChanged(object sender, EventArgs e)
        {
            Encrypt encrypt = new Encrypt();
            foreach (DataRow dr in ds.Tables[1].Rows)
            {
                if (dr[0].ToString() == combMyNum.Text && dr[1].ToString() != "")
                {
                    textBoxPSW.Text = encrypt.decode(dr[1].ToString());
                    return;
                }
            }

        }

        //删除当前信息
        private void btnDelMyNum_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
                {
                    if (ds.Tables[1].Rows[i][0].ToString() == combMyNum.Text)
                    {
                        ds.Tables[1].Rows.RemoveAt(i);
                    }
                }
                labResult.Visible = true;
                labResult.Text = "删除号码成功";
            }
            catch (Exception)
            {
                labResult.Visible = true;
                labResult.Text = "删除号码失败";
            }
            
        }

        private void myMainFrom_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool duplication = false;
            Encrypt encrypt = new Encrypt();
            if (combMyNum.Text != "")
            {
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    if (dr[0].ToString() == combMyNum.Text)
                    {
                        duplication = true;
                        if (chbSaveOrNot.Checked == true)
                            dr[1] = encrypt.encode(textBoxPSW.Text.ToString());
                    }
                }
                if (duplication == false)
                {
                    DataRow dr = ds.Tables[1].NewRow();
                    dr[0] = combMyNum.Text;
                    if (chbSaveOrNot.Checked == true)
                        dr[1] = encrypt.encode(textBoxPSW.Text.ToString());
                    ds.Tables[1].Rows.Add(dr);
                }
            }
            if (ds.Tables[1].Rows.Count > 1)
            {
                for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
                {
                    if (ds.Tables[1].Rows[i][0].ToString() == "")
                    {
                        ds.Tables[1].Rows.RemoveAt(i);
                    }
                }
            }
            if (ds.Tables[0].Rows.Count > 1)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i][1].ToString() == "" & ds.Tables[0].Rows[i][0].ToString() == "")
                    {
                        ds.Tables[0].Rows.RemoveAt(i);
                    }
                }
            }
            if (System.IO.File.Exists("PhoneNum.xml"))
            {
                System.IO.File.Delete("PhoneNum.xml");
            }
            ds.WriteXml("PhoneNum.xml");
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                sendThread.Abort();
                sendThread.Join();
                labResult.Text = "发送终止";
            }
            catch (Exception)
            {

                labResult.Text = "发送终止";
            }
           

        }


        

    }
}
